package db

import (
	"pmservice/graph/model"

	gonanoid "github.com/matoous/go-nanoid/v2"
	"gorm.io/gorm"
)

type Admin struct {
	gorm.Model
	UID      string
	Hospital string
	Account  string
	Password string
}

func (Admin) TableName() string {
	return "admin"
}

func (d *Admin) FromGQLNew(in *model.AdminNew) {
	d.Hospital = in.Hosuid
	d.Account = in.Account
	d.Password = in.Password
}

func (d *Admin) FromGQLEdit(in *model.AdminEdit) []string {
	fields := []string{}
	if in.Account != nil {
		d.Account = *in.Account
		fields = append(fields, "account")
	}
	return fields
}

func (d *Admin) ToGQL() *model.Admin {
	return &model.Admin{
		UID:      d.UID,
		Account:  d.Account,
		Password: d.Password,
	}
}

func AdminGet(dbs *gorm.DB, uid string) *Admin {
	d := Admin{}
	result := dbs.Where("uid=?", uid).Take(&d)
	if result.Error != nil {
		return nil
	}
	return &d
}

// 检查账号名是否已被使用
func AdminExist(dbs *gorm.DB, hosuid string, except string, account string) bool {
	d := Admin{}
	result := dbs
	if except == "" {
		result = dbs.Where("account=?", account).Take(&d)
	} else {
		result = dbs.Where("account=? AND uid!=?", account, except).Take(&d)
	}
	return result.Error == nil && result.RowsAffected > 0
}

func AdminNew(dbs *gorm.DB, input *model.AdminNew) (*Admin, error) {
	d := Admin{
		UID: gonanoid.Must(),
	}
	d.FromGQLNew(input)
	// 创建账号
	result := dbs.Create(&d)
	if result.Error != nil {
		return nil, result.Error
	}
	return &d, nil
}

func AdminSave(dbs *gorm.DB, hosuid string, uid string, input *model.AdminEdit) bool {
	d := Admin{}
	fields := d.FromGQLEdit(input)
	result := dbs.Where("uid=? AND hospital=?", uid, hosuid).
		Select(fields).
		Updates(&d)
	if result.Error != nil || result.RowsAffected == 0 {
		return false
	}
	return true
}

func AdminDel(dbs *gorm.DB, uid string) bool {
	result := dbs.Where("uid=?", uid).Delete(&Admin{})
	return result.Error == nil && result.RowsAffected > 0
}

func AdminLogin(dbs *gorm.DB, account string, password string) *Admin {
	d := Admin{}
	result := dbs.Where("account=? AND password=?", account, password).Take(&d)
	if result.Error != nil {
		return nil
	}
	return &d
}

func AdminUpdatePassword(dbs *gorm.DB, uid string, oldpass string, newpass string) bool {
	d := Admin{
		UID:      uid,
		Password: newpass,
	}
	fields := []string{"password"}
	result := dbs
	result = result.Where("uid=? AND password=?", uid, oldpass).
		Select(fields).
		Updates(&d)
	if result.Error != nil || result.RowsAffected == 0 {
		return false
	}
	return true
}
